package com.swk.form;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 防表单重复提交
 */
@WebServlet("/form")
public class FormServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public FormServlet() {
        super();
    }

	/**
	 * 服务器生成表单
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
		response.setCharacterEncoding("UTF-8");

		String token = TokenUtils.getInstance().generateToken();
		request.getSession(true).setAttribute("token", token);// token存入session

		//写表单，将token放入表单中
		PrintWriter out = response.getWriter();
		out.write("<form action='" + request.getContextPath() + "/form' method='post'>");
		out.write("<input type='hidden' name='token' value='" + token + "'/>");
		out.write("<input type='text' name='username'/>");
		out.write("<input type='submit' value='提交'/>");
		out.write("</form>");
		out.flush();
		out.close();
	}

	/**
	 * 处理表单提交请求
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		//校验token是否有效
		if(!TokenUtils.getInstance().isToken(request)){//无效
			System.out.println("重复提交");
			return;
		}
		//用户的令牌有效，处理提交，并移除令牌
		request.getSession().removeAttribute("token");
		//处理表单参数
		String username = request.getParameter("username");
		System.out.println(username + "已存到数据库");
		response.sendRedirect(request.getContextPath() + "/index.jsp");
	}

}
